package test.study.java.jol.samples;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;

@Slf4j
public class JOLSample_13_ThinLocking {

    /*
     * This is another dive into the mark word.
     *
     * This one is the example of thin (displaced) lock. The data
     * in mark word when lock is acquired is the reference to the
     * displaced _3_object header, allocated on stack. Once we leave
     * the lock, the displaced header is discarded, and mark word
     * is reverted to the default value.
     *
     * This example relies on biased locking not biasing the _3_object
     * at the first lock acquisition. Since JDKs up to 8 have biased
     * locking startup delay, this example works out of the box there.
     * On modern JDKs, starting with 9, this example should be run
     * with with -XX:-UseBiasedLocking.
     */
    public static void main(String[] args) {
        log.info(VM.current().details());

        final A a = new A();

        ClassLayout layout = ClassLayout.parseInstance(a);

        log.info("**** Fresh _3_object");
        log.info(layout.toPrintable());

        synchronized (a) {
            log.info("**** With the lock");
            log.info(layout.toPrintable());
        }

        log.info("**** After the lock");
        log.info(layout.toPrintable());
    }

    public static class A {
        // no fields
    }
}
